using MVCWeekOne.Models;

namespace MVCWeekOne.Services
{
    /// <summary>
    /// API配置验证服务
    /// </summary>
    public class ApiConfigurationValidator
    {
        /// <summary>
        /// 验证API配置
        /// </summary>
        /// <param name="apiSettings">API设置</param>
        /// <returns>验证结果</returns>
        public static (bool IsValid, string ErrorMessage) ValidateConfiguration(ApiSettings apiSettings)
        {
            if (apiSettings == null)
            {
                return (false, "API配置不能为空");
            }

            if (string.IsNullOrWhiteSpace(apiSettings.ReadApiUrl))
            {
                return (false, "读API地址不能为空");
            }

            if (string.IsNullOrWhiteSpace(apiSettings.WriteApiUrl))
            {
                return (false, "写API地址不能为空");
            }

            if (!Uri.TryCreate(apiSettings.ReadApiUrl, UriKind.Absolute, out _))
            {
                return (false, "读API地址格式无效");
            }

            if (!Uri.TryCreate(apiSettings.WriteApiUrl, UriKind.Absolute, out _))
            {
                return (false, "写API地址格式无效");
            }

            if (apiSettings.TimeoutSeconds <= 0)
            {
                return (false, "超时时间必须大于0");
            }

            if (apiSettings.RetryCount < 0)
            {
                return (false, "重试次数不能小于0");
            }

            return (true, string.Empty);
        }

        /// <summary>
        /// 检查API连通性
        /// </summary>
        /// <param name="httpClient">HTTP客户端</param>
        /// <param name="apiUrl">API地址</param>
        /// <returns>是否连通</returns>
        public static async Task<bool> CheckApiConnectivity(HttpClient httpClient, string apiUrl)
        {
            try
            {
                // 尝试访问API健康检查端点（如果有的话）
                var response = await httpClient.GetAsync($"{apiUrl}/health");
                return response.IsSuccessStatusCode;
            }
            catch
            {
                return false;
            }
        }
    }
}
